package com.nativetalk.service.rongCloud;

import com.aliyun.openservices.ClientException;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.rongyun.UserCommit;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TdNtTeacherDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RongCloudServiceImpl implements RongCloudService{

    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/" ;
    @Resource
    private RongCloudConfig rongCloudConfig;

    @Resource
    private TdNtMemberDao tdNtMemberDao;

    @Resource
    private TdNtTeacherDao tdNtTeacherDao;

    Logger logger = LoggerFactory.getLogger(RongCloudServiceImpl.class);

    @Transactional
    public RetInfo getUsersToken(){
        RetInfo retInfo = new RetInfo();
        TokenResult tokenResult = null;
        try{
        Reader reader = null ;
        String appKey = rongCloudConfig.getAppkey();
        String appSecret = rongCloudConfig.getSecret();
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        Map<String,Object> map = new HashMap<>();
        //重新获取学生的融云token
        List<UserCommit> studentCommitList = new ArrayList<>();
            studentCommitList = tdNtMemberDao.selectUsersRongCloud();
        for(UserCommit studentCommit:studentCommitList){
            if(studentCommit.getRongcloud_token()!= null && studentCommit.getRongcloud_token()!=""){
                map.put(studentCommit.getUserId(),studentCommit.getRongcloud_token());
            }else{
                String memb_head_portraituri = studentCommit.getPortraitUri();
                if(!memb_head_portraituri.contains("http")){
                    memb_head_portraituri = WAIJIAOJUN_URL + memb_head_portraituri;
                }
                tokenResult = rongCloud.user.getToken("student"+studentCommit.getUserId(),studentCommit.getName(),memb_head_portraituri);
                tdNtMemberDao.updateRongCloudToken(tokenResult.token, Integer.valueOf(studentCommit.getUserId()));
                map.put(studentCommit.getUserId(),tokenResult.getToken());
                logger.info(tokenResult.toString());
            }
        }
        //重新获取老师的融云token
            List<UserCommit> teacherCommitList = new ArrayList<>();
            teacherCommitList = tdNtTeacherDao.selectTeachersRongCloud();
            for(UserCommit teacherCommit:teacherCommitList){
                if(teacherCommit.getRongcloud_token()!= null && teacherCommit.getRongcloud_token()!=""){
                    map.put(teacherCommit.getUserId(),teacherCommit.getRongcloud_token());
                }else{
                    String memb_head_portraituri = teacherCommit.getPortraitUri();
                    if(!memb_head_portraituri.contains("http")){
                        memb_head_portraituri = WAIJIAOJUN_URL + memb_head_portraituri;
                    }
                    tokenResult = rongCloud.user.getToken("teacher"+teacherCommit.getUserId(),teacherCommit.getName(),memb_head_portraituri);
                    tdNtTeacherDao.updateTeachersRongCloudToken(tokenResult.token, Integer.valueOf(teacherCommit.getUserId()));
                    map.put(teacherCommit.getUserId(),tokenResult.getToken());
                    logger.info(tokenResult.toString());
                }
            }
        retInfo.setMark(RetInfo.ReturnCode.SUCCESS);
        retInfo.setTip(RetInfo.ReturnCode.SUCCESS_MSG_CN);
        retInfo.setObj(map);
        }catch(IllegalArgumentException e){
            retInfo.setTip(tokenResult.getErrorMessage());
            retInfo.setObj(e.getMessage());
            logger.error(e.getMessage(),e);
            return retInfo;
        }catch (Exception e) {
            retInfo.setTip(tokenResult.getErrorMessage());
            retInfo.setObj(e.getMessage());
            logger.error(e.getMessage(),e);
            return retInfo;
        }
        return retInfo;
    }

    public UserCommit getUserById(String userId){
        UserCommit userCommit = new UserCommit();
        if(userId.contains("student")){
            Integer memb_id=Integer.parseInt(userId.replace("student",""));
            userCommit=tdNtMemberDao.selectStudentMessageById(memb_id);
        }else if(userId.contains("teacher")){
            Integer tea_id=Integer.parseInt(userId.replace("teacher",""));
            userCommit=tdNtTeacherDao.selectTeacherMessageById(tea_id);
        }else{
            throw new ClientException("userId is wrong");
        }
        return userCommit;
    }
}
